//
//  FCSingletonObject.m
//  Fontcase
//
//  Created by Pieter Omvlee on 8/16/08.
//  Copyright 2008 Insearchofaname. All rights reserved.
//

#import "CHSingletonObject.h"

static NSMutableDictionary *singletons;

void CHRegisterSingleton (id singleton)
{
  if (!singletons)
    singletons = [[NSMutableDictionary alloc] init];
  
  [singletons setValue:singleton forKey:[singleton className]];
}

@implementation CHSingletonObject

+ (id)sharedController
{
  if (!singletons)
    singletons = [[NSMutableDictionary alloc] init];
  
  NSString *key = NSStringFromClass([self class]);
  
  id singleton = [singletons valueForKey:key];
  if (!singleton) {
    singleton = [[NSClassFromString(key) alloc] init];
    [singletons setValue:singleton forKey:key];
  }
  
  return singleton;
}

- (id)init
{
  self = [super init];
  if (self != nil)
    CHRegisterSingleton(self);
  return self;
}

- (void)awakeFromNib
{
  CHRegisterSingleton(self);
}

@end

#pragma mark -

@implementation CHSingletonViewController

+ (id)sharedController
{
  if (!singletons)
    singletons = [[NSMutableDictionary alloc] init];
  
  NSString *key = NSStringFromClass([self class]);
  
  id singleton = [singletons valueForKey:key];
  if (!singleton) {
    singleton = [[self alloc] initWithNibName:key bundle:nil];
    [singletons setValue:singleton forKey:key];
  }
  return singleton;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
  self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
  if (self)
    CHRegisterSingleton(self);
  return self;
}

- (void)awakeFromNib
{
  CHRegisterSingleton(self);
}

@end

#pragma mark -

@implementation CHSingletonWindowController

+ (id)sharedController
{
  if (!singletons)
    singletons = [[NSMutableDictionary alloc] init];
  
  NSString *key = NSStringFromClass([self class]);
  
  id singleton = [singletons valueForKey:key];
  if (!singleton) {
    singleton = [[self alloc] initWithWindowNibName:key];
    [singletons setValue:singleton forKey:key];
  }
  return singleton;
}

- (id)initWithWindowNibName:(NSString *)nibName
{
  self = [super initWithWindowNibName:nibName];
  if (self)
    CHRegisterSingleton(self);
  return self;
}

- (void)awakeFromNib
{
  CHRegisterSingleton(self);
}

@end

@implementation CHSingletonResponder : NSResponder

+ (id)sharedController
{
  if (!singletons)
    singletons = [[NSMutableDictionary alloc] init];
  
  NSString *key = NSStringFromClass([self class]);
  
  id singleton = [singletons valueForKey:key];
  if (!singleton) {
    singleton = [[self alloc] init];
    [singletons setValue:singleton forKey:key];
  }
  return singleton;
}

- (id)init
{
  self = [super init];
  if (self)
    CHRegisterSingleton(self);
  return self;
}

- (void)awakeFromNib
{
  CHRegisterSingleton(self);
}

@end

